<?php

namespace app\admin\model;


//易联云打印
use app\admin\data\sdk\yilianyun\oauth\YlyOauthClient;
use App\Api\PrinterService;
use app\common\model\Config;

require_once ROOT_PATH.'application/admin/data/sdk/yilianyun/Oauth/YlyOauthClient.php';
require_once ROOT_PATH.'application/admin/data/sdk/yilianyun/Config/YlyConfig.php';

class YlyPrinter
{


    /**
     * 添加易联云打印机授权
     * @param $param
     * @return array|mixed
     */
    public function addPrinterYly($param)
    {
        $yly_config = new YlyConfig($param[ 'open_id' ], $param[ 'apikey' ]);

        $access_token = $this->getYlyToken($yly_config);
        //添加打印机
        $printer = new PrinterService($access_token, $yly_config);
        $data = $printer->addPrinter($param[ 'printer_code' ], $param[ 'printer_key' ], '', '');
        if (isset($data->error) && $data->error == 0) {
            return true;
        } else {
            return $data;
        }
    }

    /**
     * 获取易联云token
     * @param $yly_config
     * @param
     * @return mixed
     */
    public function getYlyToken($yly_config)
    {
        $config_model = new Config();
        //token配置
        //$config = $config_model->getConfig(['name'=>'yly']);
        $config  = \app\common\model\Config::get(['name'=>'yly']);

        $value = $config?json_decode($config->value,true):[];

        //$config_data = $this->getYlyTokenConfig();
        //$config = $config_data[ 'data' ][ 'value' ];

        $client = new YlyOauthClient($yly_config);

        if (!isset($config->value)||$value[ 'end_time' ] == 0 || $value[ 'end_time' ] < time()) {

            $token = $client->getToken();           //若是开放型应用请传授权码code

            $access_token = $token->access_token;   //调用API凭证AccessToken

            //更新token
            $expires_in = $token->expires_in;
            $end_time = strtotime('+' . $expires_in / 86400 . 'day');
            $token_data = [
                'access_token' => $token->access_token,
                'end_time' => $end_time
            ];
            $data = [
                //'name'=>'yly',
                'group'=>'print',
                'title'=>'易联云打印机token',
                'type'=>'array',
                'value'=>json_encode($token_data,320)
            ];

            $res = $config_model->save($data,['name'=>'yly']);
            //$this->setYlyTokenConfig($token_data);
        } else {
            $access_token = $value[ 'access_token' ];
        }

        return $access_token;
    }

    public function deletePrinterYly($param)
    {

        $yly_config = new YlyConfig($param[ 'open_id' ], $param[ 'apikey' ]);

        $access_token = $this->getYlyToken($yly_config);

        //添加打印机
        $printer = new PrinterService($access_token, $yly_config);
        $data = $printer->deletePrinter($param[ 'printer_code' ]);
        if (isset($data->error) && $data->error == 0) {
            return true;
        } else {
            return $data;
        }
    }
}